package com.dba.example.gwt.client.commands.impl;

import javax.inject.Inject;

import com.dba.example.gwt.client.beans.Company;
import com.dba.example.gwt.client.beans.factories.CompanyAutoBeanFactory;
import com.dba.example.gwt.client.commands.CompanySaveCallback;
import com.dba.example.gwt.client.commands.RequestBuilderCommand;
import com.google.gwt.http.client.Request;
import com.google.gwt.user.client.Command;
import com.google.inject.assistedinject.Assisted;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;
import com.google.web.bindery.autobean.shared.Splittable;

public class CompanySaveCommand extends RequestBuilderCommand implements Command  {
	
	private CompanyAutoBeanFactory factory;
	
	private AutoBean<Company> company;
	
	private CompanySaveCallback callback;
	
	@Inject
	public CompanySaveCommand(CompanyAutoBeanFactory factory, @Assisted AutoBean<Company> company, @Assisted CompanySaveCallback callback) {
		this.factory = factory;
		this.company = company;
		this.callback = callback;
	}

	@Override
	public void execute() {
		Splittable splittable = AutoBeanCodex.encode(company);
		postRequest("rest/company/save", splittable.getPayload());
	}
	
	public void success(String json) {
		AutoBean<Company> bean = AutoBeanCodex.decode(factory, Company.class, json);
		callback.success(bean);
	}

	public void error(Request request, Throwable exception) {
		callback.error(exception.getMessage());
	}

}
